<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2016/8/9
 * Time: 15:52
 */
class SupplyChainAction extends Action{
    //供应链列表
    public function getSupplyChainList($name=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $supplyChain = M("module_supply_chain");
        Session::switchCustomer($customerId);
        $name?$where['a.name']=array('like',"%$name%"):"";
        $where['a.deleted']=array('eq',0);
        $where['b.status']=array("neq",'close');
        $arr = $supplyChain->alias("a")
            ->join("inner join wx_customer_user b on a.customerUserId=b.id")
            ->field("a.*,b.fullName")
            ->order("a.updateTime desc")
            ->limit($start,$limit)
            ->where($where)
            ->select();
        if($arr){
            $count = $supplyChain->alias("a")
                ->join("inner join wx_customer_user b on a.customerUserId=b.id")
                ->where($where)
                ->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //获得供应链设置
    public function getSupplyById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $supplyChain = M("module_supply_chain");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        $result = $supplyChain->alias("a")
            ->join("inner join wx_customer_user b on a.customerUserId=b.id")
            ->field("a.id,a.name,b.customerId,b.fullName")
            ->find();
        if($result){
            Output::instance()->object($result);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    //删除供应链
    public function delSupplyChainById($id,$customerUserId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $supplyChain = M("module_supply_chain");
        $customerUser = M("customer_user");
        $vendorModel = M("mivendor");
        Session::switchCustomer($customerId);
        $supplyChainInfo = $supplyChain->where("id=$id")->find();
        $data['deleted']=1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $supplyChain->startTrans();
        $delResult = $supplyChain->where("id=$id")->save($data);
        $userResult = $customerUser->where("id=$customerUserId")->setField("supplyRelation",0);
        $channelData['supplyChainId']=null;
        $channelData['supplyRelation']=0;
        $channelResult = $customerUser->where("supplyChainId=$id")->save($channelData);
        if($supplyChainInfo['vId']){
            $vendorResult = $vendorModel->where("id=".$supplyChainInfo['vId'])->save($data);
            if($vendorResult===false){
                $supplyChain->rollback();
                Output::instance()->resultCode(code_sql_error);
                return;
            }
        }
        if($delResult!==false&&$userResult!==false&&$channelResult!==false){
            $supplyChain->commit();
            Output::instance()->resultCode();
        }else{
            $supplyChain->rollback();
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //供应链下的渠道列表
    public function channelListOfSupply($id=null,$fullName=null,$start=0,$limit=10,$isAll=0){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        if(!$id){
            $id=$customerUser->where("customerId=$customerId and agent='business'")->getField("supplyChainId");
        }
        if(!$id){
            Output::instance()->resultCode();
            return;
        }
        $where['supplyChainId']=array('eq',$id);
        $where['supplyRelation']=array('eq',2);
        $where['status']=array('neq','close');
        $fullName?$where['fullName']=array("like","%$fullName%"):"";
        if(!$isAll){
            $arr = $customerUser->where($where)->limit($start,$limit)->select();
        }else{
            $arr = $customerUser->where($where)->select();
        }
        if($arr){
            $count = $customerUser->where($where)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //删除供应链下的渠道
    public function delChannelById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
        $supplyBalance = M("supply_chain_balance");
        Session::switchCustomer($customerId);
        $data['supplyRelation']=0;
        $data['supplyChainId']=NULL;
        $result = $customerUser->where("id=$id")->save($data);
        $supplyBalance->where("channelId=$id and deleted=0")->setField("deleted",1);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //不是供应链或渠道商的账号列表
    public function notSupplyCUserList($fullName=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        $where['agent']=array('eq',"business");
        $where['supplyRelation']=array('eq',0);
        $fullName?$where['fullName']=array('like',"%$fullName%"):"";
        $arr = $customerUser->where($where)->limit($start,$limit)->select();
        if($arr){
            $count = $customerUser->where($where)->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    //添加供应链
    public function saveSupplyChain($name,$customerUserId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $supplyChain = M("module_supply_chain");
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);

        $customerUserInfo = $customerUser->where("id=$customerUserId")->find();
        $data['name']=$name;
        $data['cId']=$customerUserInfo['customerId'];
        $data['customerUserId']=$customerUserId;
        $data['deleted']=0;
        $data['updateTime']=date("Y-m-d H:i:s");
        $data['createTime']=date("Y-m-d H:i:s");
        $result = $supplyChain->add($data);
        if($result){
            $userData['supplyRelation']=1;
            $userData['supplyChainId']=$result;
            $userData['updateTime']=date("Y-m-d H:i:s");
            $userResult = $customerUser->where("id=$customerUserId")->save($userData);
            if($userResult!==false){
                Output::instance()->resultCode();
                return;
            }
        }
        Output::instance()->resultCode(code_sql_error);
    }
    //添加渠道
    public function addChannelToSupply($ids,$supplyId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
        $supplyBalance = M("supply_chain_balance");
        Session::switchCustomer($customerId);
        $ids = explode(',',$ids);
        $balanceData['supplyChainId']=$supplyId;
        $balanceData['updateTime']=date("Y-m-d H:i:s");
        foreach($ids as $key=>$value){
            $channelName = $customerUser->where("id=".$value)->getField("fullName");
            $balanceData['channelId']=$value;
            $balanceData['channelName']=$channelName;
            $supplyBalance->add($balanceData);
        }
        $where['id']=array('in',$ids);
        $data['supplyRelation']=2;
        $data['supplyChainId']=$supplyId;
        $result = $customerUser->where($where)->save($data);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //供应链投放渠道的商品列表
    public function supplyToChannelProduct($name=null,$isRemoved=null,$serialNumber=null,$vendor=null,$tagName=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        $userId = session("id");

        Session::switchCustomer(0);
        $ProductModel  = M('module_product');
        $supplyProduct = M("module_supply_chain_product");
        $customerUser = M("customer_user");
		$supplyInfo = $customerUser->alias("a")
		->join("inner join wx_module_supply_chain b on a.supplyChainId=b.id")
		->field("a.supplyRelation,b.cId,b.id")
		->where("a.id=".$userId)
		->find();
		if(!$supplyInfo){
			Output::instance()->resultCode();
			return;
		}
		$supplyChainId =$supplyInfo['id'];
        $condition['prod.deleted']=0;
        $condition['prod.isRemoved']=0;
		$condition['prod.fromCustomerId']=$supplyInfo['cId'];
        $condition['m.module']='product';
        $condition['_string']="prod.isAllChannel=1 or supPro.cId=$customerId";
        //判断是否积分兑换参数并设置查询条件
        isset($name) && $name != null ? $condition["prod.name"] = array("like",'%'.$name.'%'):'';
        isset($isRemoved) && $isRemoved != null ? $condition["prod.isRemoved"] = array('eq',$isRemoved):'';
        isset($serialNumber) && $serialNumber ?$condition['prod.serialNumber']=array("like","%$serialNumber%"):"";
        isset($vendor) && $vendor ?$condition['ven.name']=array("like","%$vendor%"):"";
        isset($tagName) && $tagName ?$condition['tag.name']=array("like","%$tagName%"):"";
        if($tagName){
            $arr = $ProductModel->alias("prod")
                ->join("wx_module_supply_chain_product supPro on supPro.pid=prod.id")
                ->join("wx_module_product_tag_list tlist on prod.id=tlist.pid")
                ->join("wx_module_product_tag tag on tlist.tagId = tag.id")
                ->join("inner join wx_mishare m on m.moduleId=prod.id")
                ->join("wx_mivendor ven on prod.vId=ven.id")
                ->field('prod.*,m.id as sId,ven.name as supplierName')
                ->where($condition)->order("prod.updateTime desc")->group("prod.id")->limit($start, $limit)->select();
            if ($arr) {
                $arr = R("Product/resetProductList",array($arr,$arr[0]['customerId']));
                foreach($arr as $key=>$value){
                    $selResult = $ProductModel->where("supplyProId=".$value['id']." and isChainPro=1 and fromCustomerId=$customerId and deleted=0 and supplyChainId = $supplyChainId")->find();
                    if($selResult){
                        $arr[$key]['isSelect']=1;
                    }else{
                        $arr[$key]['isSelect']=0;
                    }
                }
                Session::switchCustomer($customerId);
                $count =  $ProductModel->alias("prod")
                    ->join("wx_module_supply_chain_product supPro on supPro.pid=prod.id")
                    ->join("wx_module_product_tag_list tlist on prod.id=tlist.pid")
                    ->join("wx_module_product_tag tag on tlist.tagId = tag.id")
                    ->join("inner join wx_mishare m on m.moduleId=prod.id")
                    ->join("wx_mivendor ven on prod.vId=ven.id")
                    ->field('prod.*,m.id as sId,ven.name as supplierName')
                    ->group("prod.id")
                    ->where($condition)
                    ->select();
                $count= count($count);
                Output::instance()->objArray($arr,$count);
            } else {
                Output::instance()->resultCode(code_success);
            }
        }else{
            $arr =$ProductModel->alias("prod")
                ->join("wx_module_supply_chain_product supPro on supPro.pid=prod.id")
                ->join("inner join wx_mishare m on m.moduleId=prod.id")
                ->join("wx_mivendor ven on prod.vId=ven.id")
                ->field('prod.*,m.id as sId,ven.name as supplierName')
                ->where($condition)->order("prod.updateTime desc")->group("prod.id")->limit($start, $limit)->select();
            if ($arr) {
                $arr = R("Product/resetProductList",array($arr,$arr[0]['customerId']));
                foreach($arr as $key=>$value){
                    $selResult = $ProductModel->where("supplyProId=".$value['id']." and isChainPro=1 and fromCustomerId=$customerId and deleted=0 and supplyChainId = $supplyChainId")->find();
                    if($selResult){
                        $arr[$key]['isSelect']=1;
                    }else{
                        $arr[$key]['isSelect']=0;
                    }
                }
                Session::switchCustomer($customerId);
                $count =$ProductModel->alias("prod")
                    ->join("wx_module_supply_chain_product supPro on supPro.pid=prod.id")
                    ->join("inner join wx_mishare m on m.moduleId=prod.id")
                    ->join("wx_mivendor ven on prod.vId=ven.id")
                    ->field('prod.*,m.id as sId,ven.name as supplierName')
                    ->where($condition)
                    ->count();
                Output::instance()->objArray($arr,$count);
            } else {
                Output::instance()->resultCode(code_success);
            }
        }
    }
    //批量选中
    public function copyProductsToChannel($ids){
        $ids = explode(",",$ids);
        foreach($ids as $key=>$value){
            self::copyProductToChannel($value,1);
        }
        Output::instance()->resultCode();
    }
    //复制供应链商品到渠道
    public function copyProductToChannel($id,$isSelf=0){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $productModel = M("module_product");
        $productSpec = M("module_product_specification");
        $productSpecName = M("module_product_specification_name");
        $productSpecGroup = M("module_product_specification_group");
        $shareBaseModel=M("mishare");
        $ProductTagModel = M("module_product_tag");
        $ProductTagListModel = M("module_product_tag_list");
        $shareMaterModel=M("mishare_material");
        Session::switchCustomer($customerId);
        $result = $productModel->where("isChainPro=1 and deleted=0 and supplyProId=$id and fromCustomerId=$customerId")->find();
        if($result){return true;}
        $productInfo = $productModel->alias("a")
            ->join("inner join wx_module_supply_chain b on a.fromCustomerId=b.cId")
            ->field("a.*,b.id as supplyId")
            ->where("a.id=$id and b.deleted=0")->find();
        $oldProductCid = $productInfo['fromCustomerId'];
        $productInfo['fromCustomerId']=$customerId;
        $productInfo['supplyProId']=$id;
        $productInfo['supplyChainId']=$productInfo['supplyId'];
        $productInfo['isChainPro']=1;
        $productInfo["createTime"]=date("Y-m-d H:i:s");
        $productInfo["updateTime"]=date("Y-m-d H:i:s");
        unset($productInfo['id']);
        unset($productInfo['serialNumber']);
        unset($productInfo['salesCount']);
        unset($productInfo['supplyId']);
        unset($productInfo['isAllChannel']);
        $newId = $productModel->add($productInfo);
        if($productInfo['supportSpecification']){
            $groupWhere['fromCustomerId']=array("eq",$oldProductCid);
            $groupWhere['pid'] = array("eq",$id);
            $groupInfo = $productSpecGroup->where($groupWhere)->select();
            foreach($groupInfo as $i=>$group){
                $groupData = null;
                $groupData['groupName']=$group['groupName'];
                $groupData['fromCustomerId']=$customerId;
                $groupData['pid']=$newId;
                $groupData['updateTime']=date("Y-m-d H:i:s");
                $groupData['spetype']=0;
                $groupId = $productSpecGroup->add($groupData);
                $nameList = $productSpecName->where("groupId=".$group['id'])->select();
                foreach($nameList as $j=>$name){
                    $nameData=null;
                    $nameData['groupId']=$groupId;
                    $nameData['specificationName']=$name['specificationName'];
                    $nameData['updateTime']=date("Y-m-d H:i:s");
                    $nameData['specificationUrl']=$name['specificationUrl'];
                    $nameId= $productSpecName->add($nameData);
                    $specArray[$name['specificationName']]=$nameId;
                }
            }
            $productSpecList = $productSpec->where("pid=$id")->select();
            foreach($productSpecList as $k=>$spec){
                unset($spec['id']);
                unset($spec['serialNumber']);
                $spec['pid']=$newId;
                $spec['firstSpecificId']=$specArray[$spec['firstSpecificName']];
                $spec['secSpecificId']=$specArray[$spec['secSpecificName']];
                $productSpec->add($spec);
            }
        }
        $tagList = $ProductTagListModel->alias("a")
            ->join("inner join wx_module_product_tag b on a.tagId=b.id")
            ->field("b.*")
            ->where("a.pid=$id")
            ->select();
        foreach($tagList as $l=>$tag){
            $tagWhere['fromCustomerId']=array("eq",$customerId);
            $tagWhere['name'] = array("eq",$tag['name']);
            $tagResult = $ProductTagModel->where($tagWhere)->find();
            if(!$tagResult){
                unset($tag['id']);
                $tag['fromCustomerId']=$customerId;
                $tagId = $ProductTagModel->add($tag);
            }else{
                $tagId = $tagResult['id'];
            }
            $tagData=null;
            $tagData['tagId']=$tagId;
            $tagData['pid']=$newId;
            $ProductTagListModel->add($tagData);
        }

        $shareInfo = $shareBaseModel->where("moduleId=".$id." and module = 'product'")->find();
        $shareInfo["moduleId"]=$newId;
        $shareBaseId = $shareInfo["id"];
        unset($shareInfo["id"]);
        $shareInfo["createTime"] = date("Y-m-d H:i:s");
        $newShareBaseId = $shareBaseModel->add($shareInfo);
        $shareMaterialInfo = $shareMaterModel->where("sId=".$shareBaseId)->find();
        unset($shareMaterialInfo["id"]);
        $shareMaterialInfo["sId"]=$newShareBaseId;
        $shareMaterModel->add($shareMaterialInfo);
        if(!$isSelf){
            Output::instance()->resultCode();
        }
    }
    //取消选中
    public function delSupplyProduct($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $productModel = M("module_product");
        Session::switchCustomer($customerId);
        $where['fromCustomerId']=array("eq",$customerId);
        $where['supplyProId']=array("eq",$id);
        $where['deleted']=array("eq",0);
        $where['isChainPro']=array("eq",1);
        $data['deleted']=1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result = $productModel->where($where)->save($data);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }
    }
    //当前用户是供应链还是渠道商
    public function userRaletion(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $customerUser = M("customer_user");
        Session::switchCustomer($customerId);
        $id=session("id");
        $userInfo = $customerUser->where("customerId=$customerId and agent='business'")->field("supplyRelation")->find();
        $tempUserInfo = $customerUser->where("id=$id")->field("agent")->find();
        $userInfo['agent']=$tempUserInfo['agent'];
        Output::instance()->object($userInfo);
    }
    //供应链端供应链订单
    public function supplyChainOrder($name='',$proSerialNumber=null,$orderType = NULL,$serialNumber='',$phone='',$startTime='', $endTime='',$fullName='',$price=NULL,
                                     $status=NULL,$start = 0, $limit = 15, $isExport = false,$expressNo=NULL,$channelId=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $orderModel = M("module_product_order");
        $supplyChain = M("module_supply_chain");
        $MiVendor = M("mivendor");
        $orderDetail = M("module_product_order_detail");
        Session::switchCustomer($customerId);
        $id = session("id");
        $supplyInfo = $supplyChain->where("customerUserId=$id and deleted=0")->find();
        $supplyChainId = $supplyInfo['id'];
        $condition['od.isChainOrder']=array("eq",1);
        $condition['od.supplyChainId']=array("eq",$supplyChainId);
        $condition['od.deleted'] = array('eq',0);
        if(!empty($orderType)&&$orderType!=='all'&&$orderType=="orderType"){
            $condition[$orderType]=array('eq',3);
        }else if(!empty($orderType)&&$orderType!=='all'&&$orderType=='proSource')
            $condition['od.proSource']=array('eq',1);
        else if(!empty($orderType)&&$orderType!=='all'){
            $condition[$orderType]=array('eq',1);
        }else if(!empty($orderType)&&$orderType=='all'){
            $condition["od.isTeam"]=array("eq",0);
            $condition["od.freebuy"]=array("eq",0);
            $condition["od.orderType"]=array("EXP",'is null');
        }
        $proSerialNumber?$condition['detail.serialNumber']=array("like","%$proSerialNumber%"):"";        if (!empty($serialNumber)) {
            $condition['od.serialNumber'] = array('like', "%$serialNumber%");
        }
        if (!empty($phone)) {
            $condition['od.phone'] = array('like',"%{$phone}%");
        }
        if ($startTime != '' && $endTime != '') {
            $condition['od.createTime'] = array(array('egt',$startTime),array('elt',$endTime));
        } else if ($startTime != '') {
            $condition["od.createTime"] = array('egt', $startTime);
        } else if ($endTime != '') {
            $condition["od.createTime"] = array('elt', $endTime);
        }
        if (!empty($fullName)) {
            $condition['od.fullName'] = array('like',"%{$fullName}%");
        }
        if($status != NULL){
            $condition['od.status'] = array('eq',$status);
        } else {
            $condition['od.status'] = array(array('neq', ''), array('neq', order_status_notsubmit), 'and'); // not submit order
        }
        isset($expressNo)&&$expressNo?$condition["od.expressNo"]=array('like','%'.$expressNo.'%'):"";
        $channelId?$condition['od.fromCustomerId']=array("eq",$channelId):"";
        $name?$condition['detail.name']=array("like","%$name%"):"";
        $orderList = $orderModel->alias("od")
            ->join("wx_module_product_order_detail detail on od.id=detail.oid")
            ->join("wx_customer_user cuser on od.fromCustomerId=cuser.customerId and cuser.agent='business'")
            ->field("od.id")
            ->where($condition)
            ->group("od.id")
            ->limit($start,$limit)
            ->order("od.createTime desc")
            ->select();
        foreach($orderList as $key=>$value){
            $oids[]=$value["id"];
        }
        $oids = implode(",",$oids);
        $arr = $orderModel->alias("od")
            ->join("inner join wx_module_product_order_detail detail on od.id=detail.oid")
            ->join("wx_module_product_order_detail_specification c on detail.id=c.did")
            ->join("wx_customer_user cuser on od.fromCustomerId=cuser.customerId and cuser.agent='business'")
            ->where("od.id in ($oids)")
            ->field("od.id,od.serialNumber,od.expressNo,od.fullName,detail.name,c.firstSpecificName,c.secSpecificName,
            detail.count,detail.isVendorCut,detail.isChannelCut,od.status,detail.serialNumber as proSeralNumber,od.createTime,cuser.fullName as userName")
            ->order("od.createTime desc")
            ->select();
        foreach ($arr as $key => $value) {
            $rowspan=1;
            for($i=$key+1;$i<count($arr);$i++){
                $v = $arr[$i];
                if($value['id']==$v['id']){
                    $rowspan++;
                }else{
                    break;
                }
            }
            $arr[$key]['rowspan'] = $rowspan;
        }
        if ($arr) {
            $count = $orderModel->alias("od")
                ->join("wx_module_product_order_detail detail on od.id=detail.oid")
                ->join("wx_customer_user cuser on od.fromCustomerId=cuser.customerId and cuser.agent='business'")
                ->where($condition)
                ->group("od.id")
                ->select();
            $count = count($count);
            Output::instance()->objArray($arr, $count);
        } else {
            Output::instance()->resultCode();
        }

    }
    //供应链内容
    public function supplyToChannelContent($title=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $supplyContent = M("module_supply_chain_content");
        $customerUser =M("customer_user");
        $micontent = M("micontent");
        Session::switchCustomer($customerId);
        $id = session("id");
        $supplyCid = $customerUser->alias("a")
            ->join("inner join wx_module_supply_chain b on a.supplyChainId=b.id")
            ->where("a.id=$id")->getField("b.cId");
        $where['mcont.deleted']=array("eq",0);
        $title?$where['mcont.title']=array("like","%$title%"):"";
        $where['_string']="supCon.cId=$customerId or (supCon.isAllChannel=1 and mcont.fromCustomerId=$supplyCid)";
        $arr =$supplyContent->alias("supCon")
            ->join("inner join wx_micontent mcont on supCon.contentId=mcont.id")
            ->join("LEFT JOIN  wx_micontent_tag_list as tagl ON tagl.webPageId = mcont.id")
            ->join("LEFT JOIN  wx_micontent_tag as tag ON tagl.tagId = tag.id")
            ->where($where)
            ->limit($start,$limit)
            ->field("mcont.*,GROUP_CONCAT(tag.tagName) as tagNames")
            ->order('mcont.createTime desc')
            ->group("mcont.id")
            ->select();
        foreach($arr as $key=>$value){
            $id = $value['id'];
            $result = $micontent->where("fromCustomerId=$customerId and deleted=0 and isSupplyContent=1 and supplayContentId=$id")->find();
            if($result){
                $arr[$key]['isChecked']=1;
            }else{
                $arr[$key]['isChecked']=0;
            }
        }
        if ($arr) {
            $count =$supplyContent->alias("supCon")
                ->join("inner join wx_micontent mcont on supCon.contentId=mcont.id")
                ->where($where)
                ->order('mcont.createTime desc')
                ->count();
            Output::instance()->objArray($arr,$count);
        }else{
            Output::instance()->resultCode(code_success);
        }
    }
    //渠道选中内容
    public function copyContentsToChannel($ids){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $ids = explode(",",$ids);
        foreach($ids as $key=>$value){
           self::copyContent($value);
        }
        Output::instance()->resultCode();
    }
    public function copyContent($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId=Session::$user['customerId'];
        Session::switchCustomer(0);
        $MicontentModel = M("micontent");
        $ContentTagModel = M("micontent_tag");
        $ContentTagListModel = M("micontent_tag_list");
        $shareBaseModel=M("mishare");
        $shareMaterModel=M("mishare_material");
        $supplyChain = M("module_supply_chain");
        $contentProduct = M("micontent_product_list");
        $productModel = M("module_product");
        Session::switchCustomer($customerId);
        $result = $MicontentModel->where("deleted=0 and fromCustomerId=$customerId and isSupplyContent=1 and supplayContentId=$id")->find();
        if($result){return true;}
        $MicontentModel->startTrans();
        $contentInfo = $MicontentModel->where("id=$id")->find();
        $cid = $contentInfo['fromCustomerId'];
        $supplyChainId = $supplyChain->where("cId=$cid and deleted=0")->getField("id");
        $oldId= $contentInfo['id'];
        $tags = $contentInfo['tags'];
        $oldCid = $contentInfo['fromCustomerId'];
        $contentInfo['fromCustomerId']=$customerId;
        unset($contentInfo['id']);
        unset($contentInfo['vId']);
        unset($contentInfo['tags']);
        $contentInfo['supplyChainId']=$supplyChainId;
        $contentInfo['isSupplyContent']=1;
        $contentInfo['supplayContentId']=$id;
        $newId = $MicontentModel->add($contentInfo);
        if(!$newId){
            $MicontentModel->rollback();
            Output::instance()->resultCode(code_sql_error);
            return;
        }
        $shareWhere['module']=array("eq","micontent");
        $shareWhere['moduleId']=array("eq",$oldId);
        $shareWhere['deleted']=array("eq",0);
        $shareMaterInfo = $shareMaterModel->where($shareWhere)->find();
        $shareBaseData=array(
            "module" => "micontent" ,
            "moduleId" => $newId ,
            "shareCount" => 0 ,
            "viewCount" => 0 ,
            "praiseCount" => 0 ,
            "commentCount" => 0 ,
            "createTime"=> date("Y-m-d H:i:s"),
            "deleted" => 0
        );
        $resultBase=$shareBaseModel->add($shareBaseData);
        if($resultBase ) {
            unset($shareMaterInfo['id']);
            $shareMaterInfo["sId"]=$resultBase;
            $resultMeter=$shareMaterModel->add($shareMaterInfo);
            if(!$resultMeter){
                $MicontentModel->rollback();
                Output::instance()->resultCode(code_sql_error);
                return;
            }
        }else{
            $MicontentModel->rollback();
            Output::instance()->resultCode(code_sql_error);
            return;
        }
        if ($tags) {
            $arrTag = explode(",", $tags);
            foreach($arrTag as $key=>$value){
                $tagInfo = $ContentTagModel->where("id=$value and fromCustomerId = $cid")->find();
                $tagName = $tagInfo['tagName'];
                $selfTagInfo = $ContentTagModel->where("tagName='$tagName' and fromCustomerId = $customerId")->find();
                if($tagInfo){
                    if(!$selfTagInfo){
                        $tagData['fromCustomerId']=$customerId;
                        $tagData['tagName']=$tagName;
                        $tagData['tagtplid']=1;
                        $tagId = $ContentTagModel->add($tagData);
                    }else{
                        $tagId = $selfTagInfo['id'];
                    }
                }
                $tagListData['fromCustomerId']=$customerId;
                $tagListData['webPageId']=$newId;
                $tagListData['tagId']=$tagId;
                $ContentTagListModel->add($tagListData);
            }
            $newTags = $ContentTagListModel->where("fromCustomerId=$customerId and webPageId=$newId")->field("group_concat(tagId) as tags")->find();
            $tagResult = $MicontentModel->where("id=$newId")->setField("tags",$newTags['tags']);
            if($tagResult===false){
                $MicontentModel->rollback();
                Output::instance()->resultCode(code_sql_error);
                return;
            }
        }
        $where['mcId']=$id;
        $where['fromCustomerId']=$cid;
        $productList = $contentProduct->where($where)->select();
        foreach($productList as $index=>$product){
            $productId = $product['pId'];
            $proId = $productModel->where("isChainPro=1 and supplyProId=$productId and fromCustomerId=$customerId")->getField("id");
            if($proId){
                $data['fromCustomerId']=$customerId;
                $data['mcId']=$newId;
                $data['pId']=$proId;
                $result = $contentProduct->add($data);
                if(!$result){
                    $MicontentModel->rollback();
                    Output::instance()->resultCode(code_sql_error);
                    return;
                }
            }
        }
        $MicontentModel->commit();
        return $newId;
    }
    //取消选中
    public function delSupplyContent($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $micontentModel = M("micontent");
        Session::switchCustomer($customerId);
        $where['isSupplyContent']=array("eq",1);
        $where['deleted']=array("eq",0);
        $where['supplayContentId']=array("eq",$id);
        $where['fromCustomerId']=array("eq",$customerId);
        $data['deleted']=1;
        $data['updateTime']=date("Y-m-d H:i:s");
        $result = $micontentModel->where($where)->save($data);
        if($result!==false){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
}